unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdTCPServer;

type
  TForm1 = class(TForm)
    IdTCPServer1: TIdTCPServer;
    Memo1: TMemo;
    btn1: TButton;
    btn2: TButton;
    lbl1: TLabel;
    EdtPort: TEdit;
    procedure IdTCPServer1Connect(AThread: TIdPeerThread);
    procedure IdTCPServer1Disconnect(AThread: TIdPeerThread);
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);
    procedure IdTCPServer1Execute(AThread: TIdPeerThread);
  private
    { Private declarations }
    procedure Log(Msg:String);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.IdTCPServer1Connect(AThread: TIdPeerThread);
begin
  Log(Format('Client %s:%d connected server ...',
    [AThread.Connection.Socket.Binding.PeerIP, AThread.Connection.Socket.Binding.PeerPort]));
end;

procedure TForm1.Log(Msg:String);
begin
  Memo1.Lines.Add(DateTimeToStr(Now) + ' ' + Msg);
end;

procedure TForm1.IdTCPServer1Disconnect(AThread: TIdPeerThread);
begin
  Log(Format('Client %s:%d disconnected server ...',
    [AThread.Connection.Socket.Binding.PeerIP, AThread.Connection.Socket.Binding.PeerPort]));
end;

procedure TForm1.btn1Click(Sender: TObject);
begin
  if IdTCPServer1.Active then Exit;

  try
    IdTCPServer1.DefaultPort := StrToIntDef(EdtPort.Text, 65000);
    IdTCPServer1.Active := True;
  except on e:Exception do
    Log(Format('Strat server err, info %s', [e.Message]));
  end;
end;

procedure TForm1.btn2Click(Sender: TObject);
begin
  if not IdTCPServer1.Active then Exit;

  try
    IdTCPServer1.Active := False;
  except on e:Exception do
    Log(Format('Stop server err, info %s', [e.Message]));
  end;
end;

procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
var
  RecvContent:String;
begin
  RecvContent := AThread.Connection.ReadLn();
  Log(RecvContent);
  AThread.Connection.WriteLn('Socket demo server relay ....\n');
end;

end.
